package tmt.usercenter.web.domain.converter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.io.IOException;

/**
 * Created by ThreeManTeam on 2017/5/10.
 */

@Converter
public class JsonNodeConverter implements AttributeConverter<JsonNode, String> {
	private static final ObjectMapper mapper = new ObjectMapper();

	@Override
	public String convertToDatabaseColumn(JsonNode attribute) {
		if (attribute == null) {
			return null;
		}

		String result = null;
		try {
			result = mapper.writeValueAsString(attribute);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}

		return result;
	}

	@Override
	public JsonNode convertToEntityAttribute(String dbData) {
		if (dbData == null || "".equals(dbData.trim())) {
			return null;
		}

		JsonNode node = null;
		try {
			node = mapper.readTree(dbData);
		} catch (IOException e) {
			e.printStackTrace();
		}

		return node;
	}
}
